<template>
    <div class="p-4">
      <el-card>
        <div class="flex justify-between items-center mb-4">
          <el-button type="primary" @click="dialogVisible = true,isUpdate = false">新增成绩</el-button>
        </div>
  
        <el-table :data="scoreList" border stripe style="width: 100%">
          <el-table-column prop="studentId" label="学生ID" />
          <el-table-column prop="courseId" label="课程ID" />
          <el-table-column prop="usualScore" label="平时成绩" />
          <el-table-column prop="examScore" label="考试成绩" />
          <el-table-column prop="totalScore" label="总成绩" />
          <el-table-column prop="gradeDate" label="成绩日期" />
          <el-table-column label="操作" width="160">
            <template #default="scope">
              <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
  
        <div class="pagination-container">
  <el-pagination
    v-model:current-page="pagination.currentPage"
    v-model:page-size="pagination.pageSize"
    :page-sizes="[12, 24, 48]"
    :total="pagination.total"
    layout="total, sizes, prev, pager, next, jumper"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
  />
</div>
      </el-card>
  
      <!-- 成绩新增/编辑弹窗 -->
      <el-dialog :title="formData.id ? '编辑成绩' : '新增成绩'" v-model="dialogVisible" width="500px">
        <el-form :model="formData" label-width="100px">
          
          <el-form-item label="课程ID">
            <el-select v-model="formData.courseId" @change="loadStudents" placeholder="请选择课程">
  <el-option
    v-for="course in courseOptions"
    :key="course.courseId"
    :label="`${course.courseName}（${course.time} | ${course.classroom}）`"
    :value="course.courseId"
  />
</el-select>

          </el-form-item>
          <el-form-item label="学生ID">
  <el-select v-model="formData.studentId" placeholder="请选择学生">
    <el-option
      v-for="stu in studentOptions"
      :key="stu.studentId"
      :label="`${stu.name}（${stu.studentId}）`"
      :value="stu.studentId"
    />
  </el-select>
          </el-form-item>
          <el-form-item label="平时成绩">
            <el-input-number v-model="formData.usualScore" :min="0" :max="100" />
          </el-form-item>
          <el-form-item label="考试成绩">
            <el-input-number v-model="formData.examScore" :min="0" :max="100" />
          </el-form-item>
          <el-form-item label="成绩日期">
            <el-date-picker v-model="formData.gradeDate" type="date" placeholder="选择日期" style="width: 100%;" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script setup>
  import { ref, reactive, onMounted } from 'vue'
  import { ElMessageBox, ElMessage } from 'element-plus'
  import {
    getScoreList,
    addScore,
    updateScore,
    deleteScore,
    getCoursesByTeacherId,
    getStudentsByCourseId
  } from '@/api/score.js'
  import { useUserStore } from '@/stores/user'
  
  const scoreList = ref([])
  const courseOptions = ref([])
  const searchKeyword = ref('')
  const dialogVisible = ref(false)
  const isUpdate = ref(false)
  
  const formData = reactive({
    studentId: '',
    courseId: '',
    usualScore: 0,
    examScore: 0,
    gradeDate: ''
  })

        // 分页信息
        const pagination = reactive({
        currentPage: 1,
        pageSize: 12,
        total: 0
      })
  
  const userStore = useUserStore()
  
  function loadScores() {
    getScoreList({ page: pagination.currentPage, size: pagination.pageSize, keyword: searchKeyword.value })
      .then(res => {
        scoreList.value = res.data.list || res.data || []
        pagination.total = res.data.total || (res.data.list ? res.data.list.length : (res.data.length || 0))
      })
  }

  function handleCurrentChange(page) {
  pagination.currentPage = page
  loadScores()
}

function handleSizeChange(size) {
  pagination.pageSize = size
  pagination.currentPage = 1 // 改变每页数量后跳回第一页
  loadScores()
}

  
  function loadCourses() {
    const teacherId = userStore.userInfo.id || 'admin'
    getCoursesByTeacherId(teacherId).then(res => {
      if (res.code === 0) {

        courseOptions.value = res.data || []
      } else {
        console.error('获取课程列表失败:', res.message)
      }
    }).catch(err => {
      console.error('请求课程接口出错:', err)
    })
  }

  const studentOptions = ref([])

  async function loadStudents(courseId) {
  if (!courseId) return
  try {
    const res = await getStudentsByCourseId(courseId)
    console.log(courseId)
    if (res.code === 0) {
      studentOptions.value = res.data || []
      formData.studentId = '' // 清空旧的选择（如果需要）
      console.log(res)

    } else {
      ElMessage.error('学生加载失败：' + res.message)
    }
  } catch (err) {
    ElMessage.error('请求出错：' + err.message)
  }
}



  
  function handlePageChange(page) {
    currentPage.value = page
    loadScores()
  }
  
  function handleEdit(row) {
    Object.assign(formData, row)
    dialogVisible.value = true
  }
  
  function handleDelete(row) {
    ElMessageBox.confirm('确认删除该成绩记录吗？', '提示', {
      type: 'warning'
    }).then(() => {
      deleteScore(row.studentId, row.courseId).then(() => {
        ElMessage.success('删除成功')
        if (scoreList.value.length === 1 && pagination.currentPage > 1) {
          pagination.currentPage--
        }
        loadScores()
      })
    })
  }
  
  function submitForm() {
  if (!formData.courseId || !formData.studentId) {
    ElMessage.error('课程和学生ID不能为空')
    return
  }

  const data = {
    courseId: formData.courseId,
    studentId: formData.studentId,
    usualScore: Number(formData.usualScore),
    examScore: Number(formData.examScore)
  }

  const isUpdate = scoreList.value.some(
    s => s.courseId === formData.courseId && s.studentId === formData.studentId
  )

  const action = isUpdate ? updateScore : addScore

  action(data).then(() => {
    ElMessage.success(isUpdate ? '更新成功' : '录入成功')
    dialogVisible.value = false
    loadScores()
  }).catch(() => {
    ElMessage.error(isUpdate ? '更新失败' : '录入失败')
  })
}


  
  onMounted(() => {
    loadScores()
    loadCourses()
  })
  </script>
  
  
  <style scoped>
  .el-form-item {
    margin-bottom: 16px;
  }
  .pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
}
  </style>
  